package api;
/**
 * 登录接口
 */

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import comment.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int state = -1;
        String data = null;
        String msg = "未知错误";

        //1、得到前端参数并效验
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String isadmin = req.getParameter("isadmin");
        if(!StrUtil.isBlank(username) && !StrUtil.isBlank(password)){
            //2、请求数据库验证用户名和密码
            Connection connection = DBUtil.getConnection();
            String sql = "select * from userinfo where username=? and password=?";
            if(!StrUtil.isBlank(isadmin)){
                //超管
                sql += " and isadmin=1";
            }
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2, MD5.create().digestHex(password));
            ResultSet resultSet = statement.executeQuery();
            if(resultSet.next()){
                //用户名密码正确
                state = 200;
                data = username;
                msg = "";
                //将当前登录用户保存到session中
                HttpSession session = req.getSession(true);
                //构建一个user
                UserInfo userInfo = new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                session.setAttribute(ApplicationVariable.SESSION_USER_KET , userInfo);
            }
            else {
                msg = "，登陆失败！请检查权限或账号密码的输入~";
            }
        }
        else {
            msg = "参数错误";
        }

        //3、将结果返回给前端
        resp.setContentType(ApplicationVariable.APPLICATION_JSON);
        resp.getWriter().println(JSONUtil.toJsonStr(new ResultData(state , data , msg)));
    }
}
